import {
	getStorage,
	setStorage
} from "utils/storage.js"
import {showTitleModule} from "utils/message.js" 

const roleValueOption = {
	"farmer": 0,
	"corp": 1
}

export const userStore = {
	state: {
		rawData: null,
		token: getStorage("token") || null, // 登录凭证
		screenName: getStorage("screenName") || "未登录", // 用户名
		avatar: getStorage("avatar") || null, // 用户头像
		role: getStorage("role") || null
		// status: getStorage("status") //用户身份
	},
	
	getters: {
		getState: (state) => {
			return state
		},
		getUserLoginState: (state) => {
			/* 获取用户登录状态 */
			return !!state.token
		},
		getRoleValue: (state) => {
			return roleValueOption[state.role]
		}
	},

	mutations: {
		setToken: (state, token) => {
			state.token = token
		},
		setRole: (state, role) => {
			state.role = role
		},
		setRawData: (state, rawData) => {
			state.rawData = rawData
		},
		// 登录没给用户status
		setUserStatus: (state, status) => {
			state.userStatus = status
		},
		setScreenName: (state,screenName) => {
			state.screenName = screenName
		},
		setAvatar: (state,avatar) => {
			state.avatar = avatar
		},
		clearUserState: (state) => {
			state.rawData = null
			state.token = null // 登录凭证
			state.screenName = "点击登录" // 用户名
			state.avatar = null // 用户头像
		}
	},

	actions: {
		saveToken: ({
			commit,dispatch
		}, data) => {
			const {
				avatar,
				screenName,
				token,
				role
			} = data
			setStorage("token", token)
			commit("setToken", token)
			dispatch("setUserInfo",{screenName,avatar,role})	
		},
		setUserInfo: ({commit},userData) => {
			const {screenName,avatar,role} = userData
			setStorage("screenName", screenName)
			setStorage("avatar", avatar)
			setStorage("role", role)
			commit("setScreenName", screenName)
			commit("setAvatar", avatar)
			commit("setRole", role)
		},
		userLogOut: ({commit}) => {
			setStorage("token", null)
			setStorage("screenName", null)
			setStorage("avatar", null)
			commit("clearUserState")
		},
		/* 登录过期 */
		tokenTimeOut: ({dispatch}) => {
			dispatch("userLogOut")
			showTitleModule("登录过期，请重新登录",()=>{
				uni.switchTab({
					url: '/pages/mine/mine'
				})
			})
		}
	}
}
